<?php

/**
 * Description of Repositorio
 *
 * @author  Mariano Renkine
 * @author  Fernando Arau
 */
abstract class Repositorio
{

  public $tabla;
  public $id;
  public $link = false;
  public $conexiones = 0;

  public function VerificarVersion($version, $id)
  {
    $query = "SELECT convert(BIGINT, version) FROM " . $this->tabla . " WHERE " . $this->id . " = " . $id;
    $res = $this->GetSQLFirstValue($query);
    return $res == $version;
  }

//  public function LogInsert($objeto)
//  {
//    $serializado = $objeto->getJson();
//    $usuario = $objeto->getUsuario();
//    $query = "INSERT INTO logs (tabla, accion, datos, usuario, fechaHora) 
//      VALUES('" . $this->tabla . "','" . INSERT . "' ,'" . $serializado . "', '" . $usuario . "',GETDATE()) ";
//    return $this->PostSQL($query);
//  }
//
//  public function LogUpdate(EntidadDominio $objeto)
//  {
//    $serializado = $objeto->getJson();
//    $usuario = $objeto->getUsuario();
//    $query = "INSERT INTO logs (tabla, accion, datos, usuario, fechaHora) 
//      VALUES('" . $this->tabla . "','" . UPDATE . "' ,'" . print_r($serializado,true) . "', '" . $usuario . "',GETDATE()) ";
//    return $this->PostSQL($query);
//  }
//
//  public function LogDelete($usuario)
//  {
//    $query = "INSERT INTO logs (tabla, accion, datos, usuario, fechaHora) 
//      VALUES('" . $this->tabla . "','" . DELETE . "' ,'', '" . $usuario . "',GETDATE()) ";
//    return $this->PostSQL($query);
//  }

  public function OpenDB()
  {
    $link = mssql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
    $this->conexiones++;
    mssql_select_db(DB_NAME);
    return $link;
  }

  public function CloseDB($link)
  {
    $this->conexiones--;
    if ($this->conexiones == 0)
    {
      mssql_close($link);
    }
  }

  public function GetSQL($query)
  {    
    $result = mssql_query($query);
    if ($result)
    {
      while ($row = mssql_fetch_object($result))
      {
        $ret[] = $row;
      }
      return (isset($ret)) ? $ret : false;
    } else
    {
      return false;
    }
  }

  public function GetSQLFirstValue($query)
  {
    $result = mssql_query($query);
    if ($result && mssql_num_rows($result) > 0)
      return mssql_result($result, 0, 0);
    else
      return false;
  }

  public function GetValue($key)
  {
    $query = "select _value from key_value where  _key = '" . $key . "'";
    $result = mssql_query($query);
    if ($result)
      return mssql_result($result, 0, 0);
    else
      return false;
  }

  public function PostSQL($query)
  {

    $result = mssql_query($query);
    return $result;
  }

  public function GetAllTableData($table)
  {
    return $this->GetSql("select * from $table");
  }

  public function GetTableDataByWhere($table, $where)
  {
    $query = "select * from $table where $where";
    return $this->GetSql($query);
  }

  public function GetValueByTableWhere($table, $where, $value)
  {
    $query = "select " . $value . " from $table where $where";
    $result = mssql_query($query);
    if ($result)
      return mssql_result($result, 0, 0);
    else
      return false;
  }

  public function GetInsertedId()
  {
    return $this->GetSQLFirstValue("SELECT SCOPE_IDENTITY()");
  }

  public function beginTransaction()
  {
    mssql_query("BEGIN TRANSACTION");
  }

  public function commitTransaction()
  {
    mssql_query("COMMIT TRANSACTION");
  }

  public function rollbackTransaction()
  {
    mssql_query("ROLLBACK TRANSACTION");
  }

  public function setContext($context)
  {
    return " DECLARE @Ctx varbinary(128); SELECT @Ctx = CONVERT(varbinary(128), '$context'); SET CONTEXT_INFO @Ctx; ";
  }

  public function listar()
  {
    $link = $this->OpenDB();
    $result = $this->GetAllTableData($this->tabla);
    $this->CloseDB($link);
    return $result;
  }

  public function buscar($id)
  {
    $link = $this->OpenDB();
    return $this->GetTableDataByWhere($this->tabla, $this->id . " = " . $id);
    $this->CloseDB($link);
  }

//  public function buscar($id)
//  {
//    $link = $this->OpenDB();
//    $result = $this->GetTableDataByWhere($this->tabla, $this->id . " = " . $id);
//    $this->CloseDB($link);
//    return $result;
//  }

  public function listarHabilitados()
  {
    $link = $this->OpenDB();
    $result = $this->GetTableDataByWhere($this->tabla, " deshabilitado = 0");
    $this->CloseDB($link);
    return $result;
  }

//    public function eliminar($id) {
//        $link = $this->OpenDB();
//        $query = "delete from " . $this->tabla . " where " . $this->id . " = " . $id;
//        $result = $this->PostSQL($query);
//        //$this->CloseDB($link);
//        return ($result) ? 1 : 0;
//    }
  public function eliminar($id)
  {
    $link = $this->OpenDB();
    $query = "delete from " . $this->tabla . " where " . $this->id . " = " . $id;
    $result = $this->PostSQL($query);
    $this->CloseDB($link);
    return $result;
  }

  /**
   * Convierte una fecha en una cadena con el formato Ymd para utilizar en MSSQL
   * @param Date $date
   * @return string 
   */
  public function SqlDate($fecha)
  {
    switch (strtolower(gettype($fecha)))
    {
      case "object":
        $timestamp = $fecha->getTimeStamp();
        break;
      case "string":
        $timestamp = strtotime(str_replace("/", "-", $fecha));
        break;
      case "integer":
        $timestamp = $fecha;
        break;
    }
    return date("Ymd", $timestamp);
  }

  /**
   * * Convierte una fecha en una cadena con el formato Ymd H:i para utilizar en MSSQL
   * @param type $fecha
   * @param type $hora
   * @return type 
   */
     public function SqlDateTime($fecha, $hora)
  {
    switch (strtolower(gettype($fecha)))
    {
      case "object":
        $timestamp = $fecha->getTimeStamp();
        break;
      case "string":
        if (strchr($fecha, '/'))
        {
          list($dd, $mm, $yy) = explode('/', $fecha);
          $date = sprintf('%s/%s/%s', $mm, $dd, $yy);
        } else {
          $date = $fecha;
        }
        $timestamp = strtotime($date);
        break;
      case "integer":
        $timestamp = $fecha;
        break;
    }
    return date("Ymd ", $timestamp) . $hora;
  }

}

?>
